package com.tuling.jucdemo.threadbase;

/**
 * 等待唤醒(等待通知)机制
 * 这种方法两个缺点是
 * 1.必须要加synchronized
 * 2.使用notify()有时不一定会明确通知哪个线程 没有绑定线程参数 建议使用notifyAll()
 */
public class WaitDemo {
        private static Object lock = new Object();
        private static boolean flag = true;

        public static void main(String[] args) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (lock){
                        while (flag){
                            try {
                                System.out.println("wait start .......");
                                lock.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                        System.out.println("wait end ....... ");
                    }
                }
            }).start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (flag){
                        synchronized (lock){
                            if (flag){
                                //通知
                                lock.notifyAll();
                                System.out.println("notify .......");
                                flag = false;
                            }

                        }
                    }
                }
            }).start();
        }
}
